package com.jyh.supermark.dao.impl;

import com.jyh.db.BaseDAO;
import com.jyh.supermark.dao.BuyCarDao;
import com.jyh.supermark.domain.BuyCar;
import java.util.List;

public class BuyCarDaoImpl implements BuyCarDao {
    /**
     * 展示购物车所有信息
     */
    public List<BuyCar> showBuyCar() {
        String sql = "select * from buycar";
        return BaseDAO.selectMultipleRow(sql, BuyCar.class);
    }
    // 根据购物车 id 查询单条信息
    public List<BuyCar> selectByBuyCarId(String buyCayId) {
        String sql = "select * from BuyCar where id=?";
        return BaseDAO.selectMultipleRow(sql, BuyCar.class, buyCayId);
    }

    /**
     * 向购物车添加商品对象
     * @param
     * @return
     */
    @Override
    public int add(BuyCar buyCar) {
        List<BuyCar> buyCarList = selectByBuyCarId(buyCar.getId());
        if (buyCarList.size() == 0) {// 购物车中没有相同 id 的商品
            String sql = " insert into BuyCar value (?,?,?,?)";
            return BaseDAO.updateMultipleRow(sql, buyCar.getId(), buyCar.getName(), buyCar.getPrice(), buyCar.getBuynum());
        }
        else {// 购物车中有相同 id 的商品
            Integer buyNum = BaseDAO.selectMultipleRow("select buyNum from BuyCar where id=?", BuyCar.class, buyCar.getId()).get(0).getBuynum();
            String sql = " update BuyCar set buyNum=? where id=?";
          return BaseDAO.insertOneRow(sql, buyNum + buyCar.getBuynum(), buyCar.getId());
        }
    }

    /**
     * 清空购物车
     */
    @Override
    public void clearBuyCar(List<BuyCar> buyCars) {
        String sql = "truncate buycar";
        BaseDAO.deleteOneRow(sql);
    }
}
